# -*- coding: utf-8 -*-
# @Time    : 2024/8/29 12:05
# @Author  : Alvin
# @File    : access_tokens.py
import time

from flask import current_app
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import Relationship

from app.libs.get_access_token import get_access_token
from app.models.base import Base, db


class AccessToken(Base):
    __tablename__ = 'access_tokens'
    user = Relationship("User")
    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
    access_token = Column(String(255), nullable=False)

    @staticmethod
    def insert_token_to_db(ac_token, uid):
        with db.auto_commit():
            token = AccessToken()
            token.access_token = ac_token
            token.user_id = uid
            db.session.add(token)

    @staticmethod
    def delete_token(access_token):
        access_token = AccessToken.query.filter_by(access_token=access_token).first()
        access_token.delete()

    @staticmethod
    def check_access_token(token, appid, secret):
        current_time = int(time.time())
        if current_time - token.create_time > 2 * 59 * 60:
            # 被视为过期
            access_token = get_access_token(appid, secret)
            # 软删除原先的token
            token.delete()
            return access_token
        return None

    @staticmethod
    def create_access_token(uid):
        wx_app_id = current_app.config.get('MINA_APP_ID')
        wx_secret = current_app.config.get('MINA_APP_SECRET')
        access_token = AccessToken.query.filter_by(status=1).first()
        if not access_token:
            access_token = get_access_token(wx_app_id, wx_secret)
            AccessToken.insert_token_to_db(access_token, uid)
        else:
            token = AccessToken.check_access_token(access_token, wx_app_id, wx_secret)
            access_token = access_token.access_token
            # 过期了
            if token is not None:
                access_token = token
                AccessToken.insert_token_to_db(access_token, uid)
        return access_token
